package hcb.dms.khachHang;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import hcb.dms.CameraPhotoCapture;
import hcb.dms.JSONParser;
import hcb.dms.R;
import hcb.dms.UserSessionManager;

//import android.widget.ArrayAdapter;


public class Dm_khachHang  extends Activity {
    Activity activity = null;
    private String id_khachHang ="";
    private String maKH = "";
    private String tenKH ="";
    private String diaChi = "";
    private String gpsLat = "";
    private String gpsLong = "";
    private ListView lv;

    private ProgressDialog pDialog;



    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_KHACHHANG = "khachHang";
    private static final String TAG_MAKH = "maKH";
    private static final String TAG_TENKH = "tenKH";
    private static final String TAG_DIACHI = "diaChi";
    private static final String TAG_LIENHE = "lienHe";
    private static final String TAG_DIENTHOAI = "dienThoai";
    private static final String TAG_GPSLAT = "gpsLat";
    private static final String TAG_GPSLONG = "gpsLong";

    // products JSONArray
    JSONArray products = null;
    UserSessionManager session;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dm_khach_hang);
        activity = this;//luu thong tin Activity

        session = new UserSessionManager(getApplicationContext());
        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllKhachHang().execute();

        // Get listview
        //   ListView lv = getListView();
        lv = (ListView) findViewById(R.id.list);
         this.registerForContextMenu(lv);// Dang ky ContextMenu in ListView
        /*
        public void onListItemClick(ListView parent, View v,int position,long id){
            CheckedTextView item = (CheckedTextView) v;
            Toast.makeText(this, city[position] + " checked : " +
                    item.isChecked(), Toast.LENGTH_SHORT).show();
        }
        */

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // getting values from selected ListItem
                //       view.setSelected(true);

                String pid = ((TextView) view.findViewById(R.id.txMaKH)).getText().toString();
                id_khachHang = pid;




                Toast.makeText(getApplicationContext(),
                        "Clicked on demo : " + pid,
                        Toast.LENGTH_LONG).show();
                activity.openContextMenu(lv);
                // Starting new intent
              //  Intent in = new Intent(getApplicationContext(), Edit_khachHang.class);
                // sending pid to next activity
              //  in.putExtra(TAG_MAKH, pid);
                // starting new activity and expecting some response back
              //  startActivityForResult(in, 100);

            }
        });

/*

        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
                //     Intent i = new Intent(this, ActivitySetupMenu.class);
                //     startActivity(i);
                Toast.makeText(getApplicationContext(),event.getKeyCode(), Toast.LENGTH_LONG).show();
                return true;
            }

            return super.dispatchKeyEvent(event);
        }
*/

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.dm_khach_hang, menu);
        return true;
    }
    @Override
    public void onCreateContextMenu( ContextMenu menu, View v,ContextMenu.ContextMenuInfo  menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (v.getId()==R.id.list) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu_list, menu);
        }
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.add) {
            Toast.makeText(this, "Them moi ", Toast.LENGTH_SHORT).show();
        } else if (item.getItemId() == R.id.edit) {
            Toast.makeText(this, "Sua du lieu ", Toast.LENGTH_SHORT).show();
            // Starting new intent
              Intent in = new Intent(getApplicationContext(), Edit_khachHang.class);
            // sending pid to next activity
              in.putExtra(TAG_MAKH, id_khachHang);
            // starting new activity and expecting some response back
             startActivityForResult(in, 100);
        } else if (item.getItemId() == R.id.delete) {
            Toast.makeText(this, "Xoa du lieu", Toast.LENGTH_SHORT).show();
            //CameraPhotoCapture

            Intent i = new Intent(getApplicationContext(), CameraPhotoCapture.class);
            i.putExtra(TAG_MAKH, id_khachHang);
            startActivity(i);
        } else {
            return false;
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String text = "ID: " + item.getItemId()
                + " title: " + item.getTitle();
        Toast.makeText(this, text,Toast.LENGTH_LONG).show(); Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        return true;
    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     */
    class LoadAllKhachHang extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Dm_khachHang.this);
            pDialog.setMessage("Loading Khách hàng. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         */


        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(session.KEY_USERNAME,session.getUsername()));
            params.add(new BasicNameValuePair(session.KEY_PASSWORD,session.getPassword()));
            params.add(new BasicNameValuePair(session.TAG_DANGNHAP,"OK"));
            params.add(new BasicNameValuePair(session.TAG_THAOTAC, "LDSKHTG"));

            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(session.URL, "POST", params);

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_KHACHHANG);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_MAKH);
                        String ten = c.getString(TAG_TENKH);
                        String diaChi = c.getString(TAG_DIACHI);
                        String lienHe = c.getString(TAG_LIENHE);
                        String dienThoai = c.getString(TAG_DIENTHOAI);

                        String gpsLat = c.getString(TAG_GPSLAT);
                        String gpsLong = c.getString(TAG_GPSLONG);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_MAKH, id);
                        map.put(TAG_TENKH, ten);
                        map.put(TAG_DIACHI,diaChi);
                        map.put(TAG_LIENHE,lienHe);
                        map.put(TAG_DIENTHOAI,dienThoai);
                        map.put(TAG_GPSLAT,gpsLat);
                        map.put(TAG_GPSLONG,gpsLong);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    //		Intent i = new Intent(getApplicationContext(),Edit_khuVuc.class);
                    // Closing all previous activities
                    //		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    //		startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.d("All khách hàng: ", json.toString());
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    Log.d("All khác hàng : ","abc" );
                    ListAdapter adapter = new SimpleAdapter(
                            Dm_khachHang.this, productsList,
                            R.layout.item_khach_hang, new String[]{TAG_TENKH, TAG_MAKH, TAG_DIACHI,TAG_LIENHE,TAG_DIENTHOAI},
                            new int[]
                            {R.id.txTenKH,R.id.txMaKH, R.id.txDiaChi, R.id.txLienHe,R.id.txSoDienThoai});
                    // updating listview
                    lv = (ListView) findViewById(R.id.list);
                    lv.setAdapter(adapter);
                }
            });

        }

    }


}
